//
//  JDCityUnionListViewController.swift
//  DragonWallet
//
//  Created by volantPig on 2024/4/2.
//

import UIKit
import JXSegmentedView

class JDCityUnionListViewController: JDBaseViewController {
    var myTableView: UITableView?
    var dragonUnionModels: [DragonUnionListModel?]?
    
    var headerViewLabel: UILabel?
    var dragonUserNumber: Int = 0
    
    var isFristLoad: Bool = true
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.setupUIElements()
        self.getNetData()
        self.addNotification()
        self.isFristLoad = false
        // Do any additional setup after loading the view.
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        if JDSingle.default.needRefreshDragonCityUnion && self.isFristLoad == false {
            JDSingle.default.needRefreshDragonCityUnion = false
            self.getNetData(true)
        }
    }

    func setupUIElements() {
        self.myTableView = UITableView(frame: .zero, style: .plain)
        self.view.addSubview(self.myTableView!)
        self.myTableView?.snp.makeConstraints({ make in
            make.left.right.equalTo(self.view)
            make.top.equalTo(self.view)
            make.bottom.equalTo(self.view)
        })
        self.myTableView?.delegate = self
        self.myTableView?.dataSource = self
        self.myTableView?.register(JDCityUnionListTableViewCell.self, forCellReuseIdentifier: "cityUnionListCell")
        self.myTableView?.separatorStyle = .none
        self.myTableView?.backgroundColor = color("#F5F6F8")
        
        self.myTableView?.tableHeaderView = self.customHeaderView()
        
        self.myTableView?.addRefreshHeader { [weak self] in
            self?.currentPage = 1
            self?.getNetData(true)
        }
        
        self.myTableView?.addRefreshFooter { [weak self] in
            self?.currentPage += 1
            self?.getNetData(false)
        }
        
    }
    
    override func getNetData(_ isRefresh: Bool = true) {
        
        var params = [String: Any]()
        params["pageNumber"] = self.currentPage
        params["pageSize"] = 10
        
        JDNetWorkRequest(.dragonUnionList(params)) { responseStr in
            printLog("龙商圈列表\(responseStr)")
            let commonModel = JDCommonModel.deserialize(from: responseStr, designatedPath: "")
            if commonModel?.code == "0" {
                // 成功
                if let models = [DragonUnionListModel].deserialize(from: responseStr, designatedPath: "data.records") {

                    if isRefresh {
                        self.dragonUnionModels = models
                    } else {
                        self.dragonUnionModels?.append(contentsOf: models)
                    }
                
                    if models.count < 10 {
                        self.myTableView?.reloadData()
                        self.myTableView?.noMoreData()
                        return 
                    }
                }
            }
            self.myTableView?.reloadData()
            self.myTableView?.endRefresh()
        } failure: { error in
            self.myTableView?.reloadData()
            self.myTableView?.endRefresh()
        } error: { errorCode in
            print("错误Code:\(errorCode)")
            self.myTableView?.reloadData()
            self.myTableView?.endRefresh()
        }
    }
    
    func addNotification() {
        NotificationCenter.default.addObserver(self, selector: #selector(refreshDragonUnionListAction), name: NSNotification.Name.init("refreshDragonUnionList"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(refreshDragonUserNum(_:)), name:  NSNotification.Name("refreshDragonUserNum"), object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(refreshDragonUnionListAction), name: Notification.Name("notificationRefresh"), object: nil)
    }
  
    @objc func refreshDragonUnionListAction() {
        self.currentPage = 1
        self.getNetData(true)
    }
    
    @objc func refreshDragonUserNum(_ notify: Notification) {
        
        let info = notify.userInfo
        let count = (info?["dragonUserNum"] as? Int) ?? 0
        self.dragonUserNumber = count
        self.headerViewLabel?.text = String.init(format: "尨圈人数 %zd", self.dragonUserNumber)
    }
    
    
    
    func customHeaderView() -> UIView {
        let headerView = UIView()
        headerView.frame = CGRectMake(0, 0, screenWidth, 36+16)
        headerView.backgroundColor = self.commonColor
        
        self.headerViewLabel = UILabel()
        headerView.addSubview(self.headerViewLabel!)
        self.headerViewLabel?.snp.makeConstraints({ make in
            make.left.equalTo(headerView).offset(26)
            make.height.equalTo(20)
//            make.top.equalTo(headerView)
            make.centerY.equalTo(headerView)
        })
        self.headerViewLabel?.labelConfig(textAlignment: .left, font: UIFont.systemFont(ofSize: 14, weight: .regular), textColor: color("#333333"), numberOfLines: 0)
        self.headerViewLabel?.text = String.init(format: "尨圈人数 %zd", self.dragonUserNumber)
        
        return headerView
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destination.
        // Pass the selected object to the new view controller.
    }
    */

}

extension JDCityUnionListViewController: JXSegmentedListContainerViewListDelegate {
    func listView() -> UIView {
        return view
    }

    func listDidAppear() {
        
    }

    func listDidDisappear() {
    }
}

extension JDCityUnionListViewController: UITableViewDelegate, UITableViewDataSource {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.dragonUnionModels?.count ?? 0
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "cityUnionListCell") as? JDCityUnionListTableViewCell
        
        let currentModel = self.dragonUnionModels?[indexPath.item]
        cell?.dragonUnionModel = currentModel
        printLog("龙商圈数据:\(currentModel?.toJSONString())")
        
        return cell!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {

        return 80
        return UITableView.automaticDimension
    }
    
//    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
//        return 36
//    }
//
//    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
//
//        return self.customHeaderView()
//
//    }
    
}
